<template>
  <div class="product-detail">
    <button class="back-button" @click="goBack">
      <span class="back-icon">←</span>
      <span class="back-text">返回</span>
    </button>
    <div class="detail-container">
      <!-- 左侧图片轮播 -->
      <div class="image-slider">
        <div class="main-image">
          <img :src="currentImage" :alt="product.name">
        </div>
        <div class="thumbnail-list">
          <div 
            v-for="(image, index) in product.images" 
            :key="index"
            class="thumbnail"
            :class="{ active: currentImageIndex === index }"
            @click="currentImageIndex = index"
          >
            <img :src="image" :alt="product.name">
          </div>
        </div>
      </div>

      <!-- 右侧商品信息 -->
      <div class="product-info">
        <div class="product-header">
          <h1 class="product-name">{{ product.name }}</h1>
          <button class="favorite-btn" @click="handleFavorite">
            <span class="favorite-icon">{{ isFavorite ? '❤️' : '🤍' }}</span>
          </button>
        </div>
        <div class="product-meta">
          <div class="price-info">
            <span class="price">¥{{ product.price }}</span>
            <span class="unit">/ {{ product.unit }}</span>
          </div>
          <div class="stock-info">
            <span class="stock">库存: {{ product.stock }}</span>
          </div>
        </div>

        <div class="info-section">
          <h3>商品信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">上市日期</span>
              <span class="value">{{ currentDate }}</span>
            </div>
            <div class="info-item">
              <span class="label">保存方式</span>
              <span class="value">{{ product.storage }}</span>
            </div>
            <div class="info-item">
              <span class="label">保质期</span>
              <span class="value">{{ product.shelfLife }}</span>
            </div>
            <div class="info-item">
              <span class="label">产地</span>
              <span class="value">{{ product.origin }}</span>
            </div>
          </div>
        </div>

        <div class="description-section">
          <h3>商品描述</h3>
          <p class="description">{{ product.description }}</p>
        </div>

        <div class="action-buttons">
          <el-button 
            type="primary" 
            size="large"
            class="cart-button"
            @click="addToCart"
          >
            加入购物车
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { addToCart as addToCartApi } from '../axios/cart'
import { addFavorite, deleteFavorite, getFavoriteList } from '../axios/favorite'
import { ElMessage } from 'element-plus'

const router = useRouter()

const props = defineProps({
  product: {
    type: Object,
    required: true
  }
})

const isFavorite = ref(false)
const currentImageIndex = ref(0)
const favoriteIds = ref(new Set())

const currentImage = computed(() => props.product.images[currentImageIndex.value])

const currentDate = computed(() => {
  const date = new Date()
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
})

// 获取收藏列表并判断当前商品是否已收藏
const fetchFavoriteStatus = async () => {
  if (!props.product || !props.product.id) return;
  
  try {
    console.log('获取收藏列表...');
    const response = await getFavoriteList();
    if (Array.isArray(response)) {
      // 将收藏列表中的商品ID存入Set中
      favoriteIds.value = new Set(response.map(item => item.id));
      // 判断当前商品是否在收藏列表中
      isFavorite.value = favoriteIds.value.has(props.product.id);
      console.log('当前商品收藏状态:', isFavorite.value);
    }
  } catch (err) {
    console.error('获取收藏列表失败:', err);
  }
}

// 处理收藏/取消收藏
const handleFavorite = async () => {
  if (!props.product || !props.product.id) return;

  try {
    console.log('处理收藏操作:', props.product.id, isFavorite.value ? '取消收藏' : '添加收藏');
    const response = isFavorite.value
      ? await deleteFavorite(props.product.id)
      : await addFavorite(props.product.id);
    console.log('收藏操作响应:', response);

    if (response === true || response === 1 || response.code === 1) {
      isFavorite.value = !isFavorite.value;
      // 更新收藏ID集合
      if (isFavorite.value) {
        favoriteIds.value.add(props.product.id);
      } else {
        favoriteIds.value.delete(props.product.id);
      }
      ElMessage.success(isFavorite.value ? '已添加到收藏' : '已取消收藏');
    } else {
      ElMessage.error('操作失败');
    }
  } catch (err) {
    console.error('收藏操作失败:', err);
    ElMessage.error('操作失败，请稍后重试');
  }
}

const addToCart = async () => {
  try {
    const response = await addToCartApi({
      productId: props.product.id,
      quantity: 1  // 固定数量为1
    })
    if (response.code === 1) {
      ElMessage.success('已添加到购物车')
    } else {
      ElMessage.error(response.msg || '添加到购物车失败')
    }
  } catch (err) {
    console.error('添加到购物车失败:', err)
    ElMessage.error('添加到购物车失败，请稍后重试')
  }
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchFavoriteStatus()
})
</script>

<style scoped>
.product-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
  position: relative;
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  color: #2c3e50;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 10;
}

.back-button:hover {
  transform: translateX(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  background: #f8f9fa;
}

.back-icon {
  font-size: 20px;
  font-weight: 500;
}

.back-text {
  font-weight: 500;
}

.detail-container {
  margin-top: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.image-slider {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.main-image {
  width: 100%;
  height: 400px;
  border-radius: 12px;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  overflow-x: auto;
  padding: 10px 0;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.thumbnail.active {
  opacity: 1;
  border: 2px solid #4CAF50;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.product-name {
  font-size: 32px;
  color: #2c3e50;
  font-weight: 600;
  margin: 0;
  flex: 1;
}

.favorite-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 24px;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.favorite-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.price-info {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.price {
  font-size: 36px;
  color: #e74c3c;
  font-weight: 600;
}

.unit {
  font-size: 16px;
  color: #666;
}

.stock-info {
  font-size: 16px;
  color: #666;
}

.info-section {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.info-section h3 {
  font-size: 18px;
  color: #2c3e50;
  margin: 0 0 16px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.label {
  font-size: 14px;
  color: #666;
}

.value {
  font-size: 16px;
  color: #2c3e50;
  font-weight: 500;
}

.description-section {
  padding: 20px 0;
}

.description-section h3 {
  font-size: 18px;
  color: #2c3e50;
  margin: 0 0 16px 0;
}

.description {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: auto;
}

.btn-favorite,
.btn-cart {
  flex: 1;
  height: 48px;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.btn-favorite {
  background: #fff;
  color: #666;
  border: 1px solid #ddd;
}

.btn-favorite:hover {
  background: #fff5f5;
  color: #e74c3c;
  border-color: #e74c3c;
}

.btn-cart {
  background: #4CAF50;
  color: white;
}

.btn-cart:hover {
  background: #45a049;
}

.icon {
  font-size: 20px;
}

@media (max-width: 768px) {
  .back-button {
    top: 10px;
    left: 10px;
    padding: 8px 16px;
    font-size: 14px;
  }

  .detail-container {
    margin-top: 60px;
  }

  .detail-container {
    grid-template-columns: 1fr;
  }

  .main-image {
    height: 300px;
  }

  .product-name {
    font-size: 24px;
  }

  .price {
    font-size: 28px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style> 